<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: rclark $ ($Date: 2007/07/19 22:33:16 $)
// $RCSfile: impex.tickets.php,v $ : $Revision: 1.6 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

require_once ("./modules/tickets/tickets.php");

/**
* Return the Total Pages for this Plugin
*/
function getPluginTotalPages1()
{
	global $impexDB;

	$_total = $impexDB->queryFetch("SELECT COUNT(*) AS totaltickets FROM `perlDesk_calls`;");
	$finaltotal = intval($_total["totaltickets"]);

	$totalpages = ceil($finaltotal/IMPEX_PASS);

	return $totalpages;
}


/**
* Generate a random Ticket Mask
*/
function generateTicketMask()
{
	global $_SWIFT;

	mt_srand ((double) microtime() * 1000000);
	$alpha1 = mt_rand(65,90);
	mt_srand ((double) microtime() * 1000000);
	$alpha2 = mt_rand(65,90);
	mt_srand ((double) microtime() * 1000000);
	$alpha3 = mt_rand(65,90);

	$alpha1 = chr($alpha1);
	$alpha2 = chr($alpha2);
	$alpha3 = chr($alpha3);

	$prefix = $alpha1.$alpha2.$alpha3;
	if (in_array(strtoupper($prefix), $_SWIFT["stopwords"]))
	{
		return generateTicketMask();
	}

	mt_srand ((double) microtime() * 1000000);
	$num = mt_rand(100000,999999);
	$ticketmaskid = $alpha1 . $alpha2 . $alpha3 . "-" . $num;

	return $ticketmaskid;
}

/**
* Run the specific page for plugin
*/
function runPluginPage1($page)
{
	global $dbCore, $impexDB, $_IMPEXHASH, $_SWIFT;

	// Import Tickets! The big tough crap function.
	if (empty($_POST["ticketstartat"]))
	{
		$_startat = 1;
	} else {
		$_startat = intval($_POST["ticketstartat"]);
	}

	$ticketidlist = $ticketlist = $ticketidcharlist = $ticketidpointer = $newticketpointer = array();

	// First get all the tickets
	$impexDB->query("SELECT * FROM `perlDesk_calls` WHERE `id` >= '". intval($_startat) ."' ORDER BY `id` ASC LIMIT ". intval(IMPEX_PASS) .";");
	while ($impexDB->nextRecord())
	{
		_impexProcessSlashVariables($impexDB->Record);

		$ticketidlist[] = $impexDB->Record["id"];
		$ticketidcharlist[] = $impexDB->Record["ticketid"];
		$ticketidpointer[$impexDB->Record["ticketid"]] = $impexDB->Record["id"];
		$ticketlist[$impexDB->Record["id"]] = $impexDB->Record;
		$ticketlist[$impexDB->Record["id"]]["posts"][0]["fullname"] = $impexDB->Record["email"];
		$ticketlist[$impexDB->Record["id"]]["posts"][0]["email"] = $impexDB->Record["email"];
		$ticketlist[$impexDB->Record["id"]]["posts"][0]["dateline"] = returnPerlDeskTimestamp($impexDB->Record["time"]);
		$ticketlist[$impexDB->Record["id"]]["posts"][0]["subject"] = $impexDB->Record["subject"];
		$ticketlist[$impexDB->Record["id"]]["posts"][0]["creator"] = "customer";
		$ticketlist[$impexDB->Record["id"]]["posts"][0]["contents"] = $impexDB->Record["description"];
		$lastticketid = $impexDB->Record["id"];
	}

	// Now load in stuff from asTicketReply table
	$impexDB->query("SELECT * FROM `perlDesk_notes` WHERE `call` IN (". buildIN($ticketidlist) .");");
	while ($impexDB->nextRecord())
	{
		_impexProcessSlashVariables($impexDB->Record);

		$ticketidno = intval($impexDB->Record["call"]);
		$_ticket = &$ticketlist[$ticketidno];
		$_ticket["posts"][$impexDB->Record["id"]]["fullname"] = $impexDB->Record["author"];
		$_ticket["posts"][$impexDB->Record["id"]]["email"] = "";
		$_ticket["posts"][$impexDB->Record["id"]]["subject"] = "";
		$_ticket["posts"][$impexDB->Record["id"]]["contents"] = $impexDB->Record["comment"];
		$_ticket["posts"][$impexDB->Record["id"]]["creator"] = "customer";
		$_ticket["posts"][$impexDB->Record["id"]]["dateline"] = returnPerlDeskTimestamp($impexDB->Record["time"]);
	}

	// By now, almost all data should be loaded.. insert the tickets first
	foreach ($ticketlist as $key=>$val)
	{
		$newdepartmentid = intval($_IMPEXHASH["departmentpointer"][$val["category"]]);
		if (empty($newdepartmentid))
		{
			displayStatus("<font color='red'>WARNING:</font> Ticket ".$val["id"]." does not have a valid department. Ignoring.");
		} else {
			if ($val["status"] == "OPEN")
			{
				$_ticketstatusid = 1;
			} else if ($val["status"] == "HOLD") {
				$_ticketstatusid = 2;
			} else if ($val["status"] == "CLOSED") {
				$_ticketstatusid = 3;
			} else {
				$_ticketstatusid = 1;
			}
			
			$ticketid = _impexInsertTicket(generateTicketMask(), $newdepartmentid, $_ticketstatusid, 1, "0", "0", "0", "0", $val["email"], $val["email"], $val["email"], $val["subject"], $val["dateline"], $val["dateline"], count($val["posts"]), POST_CLIENT);

			$firstpostid = $lastpostid = 0;
			$lastactivity = $val["dateline"];

			foreach ($val["posts"] as $postkey=>$postval)
			{
				$_creator = POST_CLIENT;
				$_originalname = $postval["fullname"];
				$postval["fullname"] = $val["email"];
				$postval["email"] = $val["email"];

				if (is_array($_IMPEXHASH["staffuserpointer"][$_originalname]))
				{
					$postval["fullname"] = $_IMPEXHASH["staffuserpointer"][$_originalname][1];
					$postval["email"] = $_IMPEXHASH["staffuserpointer"][$_originalname][2];
					$_creator = POST_STAFF;
				} else if (is_array($_IMPEXHASH["staffdatapointer"][$_originalname])) {
					$postval["fullname"] = $_IMPEXHASH["staffdatapointer"][$_originalname][1];
					$postval["email"] = $_IMPEXHASH["staffdatapointer"][$_originalname][2];
					$_creator = POST_STAFF;
				} else if (!empty($val["fullname"]) || !empty($val["email"])) {
					$postval["fullname"] = $val["email"];
					$postval["email"] = $val["email"];
					$_creator = POST_CLIENT;
				}
				

				$_ticketpostid = _impexInsertTicketPost($ticketid, $postval["dateline"], "0", $postval["fullname"], $postval["email"], "", $postval["subject"], $postval["ipaddress"], $_creator, 0, 0, $postval["contents"]);
				$lastreplier = $postval["fullname"];
				$lastactivity = $postval["dateline"];
				if (empty($firstpostid))
				{
					$firstpostid = $_ticketpostid;
				}
				$lastpostid = $_ticketpostid;
			}

			$dbCore->query("UPDATE `". TABLE_PREFIX ."tickets` SET `lastreplier` = '". $dbCore->escape(iif(empty($lastreplier), $val["fullname"], $lastreplier)) ."', `lastactivity` = '". intval($lastactivity) ."', `firstpostid` = '". intval($firstpostid) ."', `lastpostid` = '". intval($lastpostid) ."' WHERE `ticketid` = '". intval($ticketid) ."';");
			$newticketpointer[$val["ticketid"]] = $ticketid;

			displayStatus("Imported Ticket: ".$val["id"]);
		}
	}

	unset($ticketlist);

	$_SWIFT["ticketstartat"] = $lastticketid+1;
}
?>